package com.itwlj.service.impl;

import com.itwlj.context.BaseContext;
import com.itwlj.dto.CartDTO;
import com.itwlj.entity.Cart;
import com.itwlj.entity.SkuSpec;
import com.itwlj.mapper.CartMapper;
import com.itwlj.service.CartService;
import com.itwlj.service.GoodsService;
import com.itwlj.service.SkuService;
import com.itwlj.vo.GoodsDetailVO;
import com.itwlj.vo.SkuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private CartMapper cartMapper;

    /**
     * 插入购物车数据
     *
     * @param cartDTO
     */
    public void inset(CartDTO cartDTO) {
        Cart cart = new Cart();
        BeanUtils.copyProperties(cartDTO, cart);
        Long userId = BaseContext.getCurrentId();
        cart.setUserId(userId);

        List<Cart> cartList = cartMapper.list(cart);

        if (cartList != null && !cartList.isEmpty()) {
            Cart firstCart = cartList.get(0);
            firstCart.setCount(firstCart.getCount() + 1);
            cartMapper.updateCountById(firstCart);
        } else {
            SkuVO skuVO = skuService.getById(cartDTO.getSkuId());

            GoodsDetailVO goodsDetailVO = goodsService.getById(skuVO.getGoodsId());
            List<SkuSpec> specsList = skuVO.getSkuSpecList();

            String attrsText = "";
            for (SkuSpec spec : specsList) {
                attrsText += spec.getName() + "：" + spec.getValueName() + "\t";
            }

            Cart userCart = Cart.builder().userId(userId).build();
            cart.setId((long) (cartMapper.list(userCart).size() + 1));
            cart.setUserId(BaseContext.getCurrentId());
            cart.setSkuId(skuVO.getId());
            cart.setName(goodsDetailVO.getName());
            cart.setAttrsText(attrsText);
            cart.setPicture(skuVO.getPicture());
            cart.setPrice(skuVO.getPrice());
            cart.setSelected(true);

            cartMapper.insert(cart);


        }

    }

    /**
     * 根据用户id查询购物车数据
     *
     * @return
     */
    public List<Cart> getByUserId() {

        Cart userCart = Cart.builder().userId(BaseContext.getCurrentId()).build();
        List<Cart> cartList = cartMapper.list(userCart);
        return cartList;
    }

    /**
     * 根据sku id删除购物车数据
     */
    public void deleteBySkuId(Long skuId) {
        cartMapper.deleteBySkuId(skuId, BaseContext.getCurrentId());
    }

    /**
     * 修改购物车商品数量
     *
     * @param skuId
     * @param count
     */
    public void updateCartCount(Long skuId, Long count) {
        cartMapper.updateCartCount(skuId, count, BaseContext.getCurrentId());
    }
}
